package com.study.tx.common.listener;

import com.alibaba.fastjson2.JSON;
import com.study.tx.common.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * Spring 事务监听机制：使用 @TransactionalEventListener 处理数据库事务提交成功后再执行操作
 * 参考 https://developer.aliyun.com/article/911413
 *
 * @author Administrator
 * @date 2022-08-29
 */
@Slf4j
public class MyTransactionListener {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void orderTransactionEvent(MyOrderTransactionEvent event) {
        Object source = event.getSource();
        Order order = event.getOrder();
        log.info(source + ":" + JSON.toJSONString(order));
        // 业务逻辑处理
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void orderItemTransactionEvent(MyOrderItemTransactionEvent event) {
        Object source = event.getSource();
        OrderItem orderItem = event.getOrderItem();
        log.info("source={}，event={}", source, JSON.toJSONString(orderItem));
        // 业务逻辑处理
    }
}
